package com.bwie.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.bwie.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;

// java example

/**
 * @author: 鑫仔
 * @description:
 * @params:
 * @return:
 * @date: 2025/8/4 14:12
 * 自动填充审计字段拦截器
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private String getCurrentUserName() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = null;
        //// 判断 requestAttributes 是否是 ServletRequestAttributes 的实例
        if ((requestAttributes instanceof ServletRequestAttributes)){
            servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        }

        HttpServletRequest request = null;
        if (servletRequestAttributes != null){
            request = servletRequestAttributes.getRequest();
        }

        //   HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String token = request.getHeader("token");
        if (StringUtils.isNotEmpty(token)) {
            return TokenUtil.getUserName(token);
        }
        return "system";
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始插入填充...");

        this.strictInsertFill(metaObject, "createBy", String.class, getCurrentUserName());
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始更新填充...");
        this.strictInsertFill(metaObject, "updateBy", String.class, getCurrentUserName());
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
    }
}